import React, { useEffect, useRef, useState } from "react";
import style from "./style.module.scss";
import timeOutIcon from "../../assets/images/icon/common resource/hdpi/common_icon_time_out_n.png";
import tollIcon from "../../assets/images/icon/common resource/hdpi/common_icon_toll_n.png";
import bought from "../../assets/images/image/hdpi/bought.png";
import { cancelVideoCollection, deleteVideoBuy } from "../../api/my";
import { useAppSelector } from "../../store/hooks";

//  我的——用户购买视频数据类型
interface UserVideoBuyItem {
  id: number;
  videoId: number;
  title: string;
  originalUrl: string;
  duration: number;
  createTime: number;
}

//  我的——用户收藏健康课堂视频数据类型
interface VideoCollectionItem {
  id: number;
  videoId: number;
  title: string;
  shearUrl: string;
  originalUrl: string;
  price: number;
  duration: number;
  whetherBuy: number;
  buyNum: number;
  createTime: number;
}

interface PropsType {
  buyItem?: UserVideoBuyItem;
  type: string;
  collectionItem?: VideoCollectionItem;
  onUpdate: () => void;
}

export const UserVideoBuyItem: React.FC<PropsType> = ({
  buyItem,
  type,
  collectionItem,
  onUpdate,
}) => {
  const userId = useAppSelector((state) => state.user.userInfo.userId);
  const sessionId = useAppSelector((state) => state.user.userInfo.sessionId);
  const [isShow, setIsShow] = useState<boolean>(true);
  const [createTime, setCreateTime] = useState<string>("");
  const videoId = buyItem?.videoId || (collectionItem?.videoId as number);
  const videoRef = useRef<HTMLVideoElement>(null);
  const handlePlay = () => {
    if (videoRef.current) {
      videoRef.current.play();
      setIsShow(false);
    }
  };

  const handleEnded = () => {
    setIsShow(true);
  };

  useEffect(() => {
    if (buyItem) {
      const createTime = new Date(buyItem.createTime)
        .toLocaleDateString()
        .split("/")
        .join("-");
      setCreateTime(createTime);
    } else if (collectionItem) {
      const createTime = new Date(collectionItem.createTime)
        .toLocaleDateString()
        .split("/")
        .join("-");
      setCreateTime(createTime);
    }
  }, []);

  const handleDelete = async () => {
    if (type === "bought") {
      await deleteVideoBuy(videoId, userId, sessionId);
      onUpdate();
    } else {
      await cancelVideoCollection(videoId, userId, sessionId);
      onUpdate();
    }
  };
  return (
    <div className={style.userVideoBuyItem}>
      <div className={style.video_wrapper}>
        <video
          width="100%"
          controls={!isShow}
          className={style.video}
          ref={videoRef}
          onEnded={() => handleEnded()}
        >
          <source
            src={buyItem?.originalUrl || collectionItem?.originalUrl}
            type="video/mp4"
          />
        </video>
        {isShow && (
          <div className={style.title}>
            {buyItem?.title || collectionItem?.title}
          </div>
        )}
        {isShow && (
          <img
            src={timeOutIcon}
            className={style.timeOut}
            onClick={() => handlePlay()}
          />
        )}
        {isShow && (
          <div className={style.duration}>
            {buyItem?.duration || collectionItem?.duration}
          </div>
        )}
        {type === "collection" && (
          <img
            src={collectionItem?.whetherBuy ? bought : tollIcon}
            alt=""
            className={
              collectionItem?.whetherBuy ? style.bought : style.tollIcon
            }
          />
        )}
        <div className={style.footer}>
          {type === "collection" ? (
            <div className={style.buyNum}>{collectionItem?.buyNum}人已购买</div>
          ) : (
            <div className={style.buyNum}></div>
          )}
          <div className={style.right}>
            <div className={style.createTime}>{createTime}</div>
            <div className={style.btn_delete} onClick={() => handleDelete()}>
              删除
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default UserVideoBuyItem;
